// ActionScript file
import flash.events.MouseEvent;
import flash.geom.Rectangle;

import mx.core.Container;

import org.flexlancer.Logger.Logger;
import org.flexlancer.managers.SelectionManager;

private var _selected:Boolean;

[Bindable]
public var Title:String = "";
[Bindable]
public var Source:Object = "";

private function OnCC():void{
	try{
		this.Selected = false;
		this.addEventListener(MouseEvent.MOUSE_DOWN,this.Me_OnMouseDown);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function Me_OnMouseDown(evt:MouseEvent):void{
	try{
		evt.stopImmediatePropagation();
		SelectionManager.AddSelection(this);
		var prt:Container = Container(this.parent);
		var bound:Rectangle = new Rectangle(0,0,prt.width - this.width,prt.height - this.height);
		this.startDrag(false,bound);
		this.addEventListener(MouseEvent.MOUSE_UP,this.Me_OnMouseUp);
		this.addEventListener(MouseEvent.MOUSE_MOVE,this.Me_OnMouseMove);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function Me_OnMouseUp(evt:MouseEvent):void{
	try{
		this.stopDrag();
		this.removeEventListener(MouseEvent.MOUSE_UP,this.Me_OnMouseUp);
		this.removeEventListener(MouseEvent.MOUSE_MOVE,this.Me_OnMouseMove);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function Me_OnMouseMove(evt:MouseEvent):void{
	try{
		//this.Title = Math.round(this.x) + "," + Math.round(this.y);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

public function set Selected(val:Boolean):void{
	try{
		this._selected = val;
		this.ApplySelection();
	}catch(err:Error){
		throw err;
	}
}

public function get Selected():Boolean{
	return this._selected;
}

public function ApplySelection():void{
	try{
		this.anchorBL.visible = this._selected;
		this.anchorBM.visible = this._selected;
		this.anchorBR.visible = this._selected;
		this.anchorML.visible = this._selected;
		this.anchorMR.visible = this._selected;
		this.anchorTL.visible = this._selected;
		this.anchorTM.visible = this._selected;
		this.anchorTR.visible = this._selected;
	}catch(err:Error){
		throw err;
	}
}

public function getXML():XML{
	try{
		/*
		<Node instanceid="101">
	      <x>70</x>
	      <y>70</y>
	      <width>50</width>
	      <height>50</height>
	      <datatype>text</datatype>
	      <data>1</data>
	    </Node>					
		*/
		var xmlObject:XML = new XML("<Node></Node>");
		xmlObject.@instanceid = this.name;
		xmlObject.x = this.x;
		xmlObject.y = this.y;
		xmlObject.width = this.width;
		xmlObject.height = this.height;
		xmlObject.datatype = "text";
		xmlObject.data = this.Title;
		this.toolTip = this.name;
		return xmlObject;
	}catch(err:Error){
		throw err;
	}
	return null;
}
